package cn.hg.solon.youcan.system.provider;

import cn.hg.solon.youcan.common.constant.AppConstants;
import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.easyquery.util.EntityQueryableUtil;
import cn.hg.solon.youcan.system.entity.Config;
import cn.hg.solon.youcan.system.entity.EqConfig;
import cn.hg.solon.youcan.system.entity.proxy.EqConfigProxy;
import cn.hg.solon.youcan.system.service.ConfigService;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.api.proxy.entity.select.EntityQueryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.solon.annotation.Db;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.convert.ConvertUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.Page;
import org.dromara.hutool.db.PageResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import java.util.List;
import java.util.Map;

/**
 * @author 胡高
 */
@Component
public class EqConfigProvider implements ConfigService {

    @Db("db1")
    private EasyEntityQuery easyEntityQuery;

    private EntityQueryable<EqConfigProxy, EqConfig> buildQuery(Page page, Map<String, Object> paraMap) {
        String type = (String) paraMap.get("type");
        String word = (String) paraMap.get("word");

        EntityQueryable<EqConfigProxy, EqConfig> entityQueryable = this.easyEntityQuery
                // FROM sys_config AS t
                .queryable(EqConfig.class)
                // WHERE t.`type` = ${type}
                .where(t -> {
                    t.type().eq(StrValidator.isNotBlank(type), type);
                    // AND (t.`name` LIKE '%${word}%' OR t.`code` LIKE '%${word}%' OR t.`value` LIKE '%${word}%')
                    t.or(StrValidator.isNotBlank(word), () -> {
                        t.name().like(word);
                        t.code().like(word);
                        t.value().like(word);
                    });
                });

        // ORDER BY ${sortField}
        return EntityQueryableUtil.applyOrderBy(entityQueryable, page);
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.ConfigService#checkUnique(cn.hg.solon.youcan.system.entity.Config)
     */
    @Override
    public boolean checkUnique(Config bean) {
        return !this.easyEntityQuery
                // FROM sys_role AS t
                .queryable(EqConfig.class)
                // WHERE t.`type` = ${bean.type} AND t.`code` = ${bean.code} AND t.`id` <> ${bean.id}
                .where(t -> {
                    t.type().eq(bean.getType());
                    t.code().eq(bean.getCode());
                    t.id().ne(ObjUtil.isNotNull(bean.getId()), bean.getId());
                }).any();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.ConfigService#delete(java.util.List)
     */
    @Tran
    @Override
    public boolean delete(List<Integer> idList) {
        for (Integer id : idList) {
            Config item = this.get(id);

            if (ObjUtil.isNotNull(item) && item.getIsSys()) {
                throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAIL,
                        "[" + item.getName() + "] 为系统参数，不允许删除！");
            }
        }

        return this.easyEntityQuery.deletable(EqConfig.class).where(t -> t.id().in(idList)).executeRows() > 0L;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.ConfigService#get(java.lang.Integer)
     */
    @Override
    public EqConfig get(Integer id) {
        return this.easyEntityQuery.queryable(EqConfig.class).whereById(id).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.ConfigService#getByTypeAndCode(java.lang.String, java.lang.String)
     */
    @Override
    public EqConfig getByTypeAndCode(String type, String code) {
        return this.easyEntityQuery.queryable(EqConfig.class)
                .where(t -> {
                    t.type().eq(type);
                    t.code().eq(code);
                })
                .firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.ConfigService#insert(cn.hg.solon.youcan.system.entity.Config)
     */
    @Tran
    @Override
    public boolean insert(Config bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException("参数代码已经存在，请更换其它值！");
        }

        EqConfig cloneBean = BeanUtil.copyProperties(bean, EqConfig.class);

        return this.easyEntityQuery.insertable(cloneBean).executeRows() > 0L;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.ConfigService#listByType(java.lang.String)
     */
    @Override
    public List<EqConfig> listByType(String type) {
        return this.easyEntityQuery.queryable(EqConfig.class).where(t -> t.type().eq(type)).toList();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.ConfigService#pageBy(int, int, java.util.Map)
     */
    @Override
    public PageResult<EqConfig> pageBy(Page page, Map<String, Object> paraMap) {
        EasyPageResult<EqConfig> pageList = this.buildQuery(page, paraMap).toPageResult(page.getPageNumber(), page.getPageSize());

        PageResult<EqConfig> result = new PageResult<>();
        result.addAll(pageList.getData());
        result.setTotal(ConvertUtil.toInt(pageList.getTotal()));

        return result;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.ConfigService#update(cn.hg.solon.youcan.system.entity.Config)
     */
    @Tran
    @Override
    public boolean update(Config bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException("参数代码已经存在，请更换其它值！");
        }

        EqConfig cloneBean = this.get(bean.getId());

        BeanUtil.copyProperties(bean, cloneBean, CopyOptions.of().setIgnoreNullValue(true));

        return this.easyEntityQuery.updatable(cloneBean).executeRows() > 0L;
    }

}
